using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;
using System.Media;

using System.Diagnostics;
using System.Text.RegularExpressions;

namespace PotonCapture
{
	public partial class MainForm : Form
	{
        protected MouseHook _mouseHook = new MouseHook();
        protected KeyboardHook _keyboardHook = new KeyboardHook();
        protected SettingForm _settingForm = new SettingForm();

        protected ScreenCapture _screenCapture = new ScreenCapture();
        protected MakePath _makePath = new MakePath();
        protected SettingForm.CaptureKeys _captuerKey = SettingForm.CaptureKeys.PrintScreen;

        public ScreenCapture ScreenCapture
        {
            get { return _screenCapture; }
        }
	
	
		public MainForm()
		{
			InitializeComponent();
		}

        protected void _mouseHook_MouseEvent(object sender, MouseHook.MouseHookEventArgs e)
        {
//            System.Diagnostics.Debug.WriteLine("mouse");
            if (e.Button == MouseButtons.Middle && _captuerKey == SettingForm.CaptureKeys.MiddleButton)
            {
                System.Diagnostics.Debug.WriteLine("middle");
                e.Cancel = true;

                //SystemSounds.Asterisk.Play();
                //_notifyIcon.Icon = Properties.Resources.MainIconCapture;
                //string savePath;
                //_capture.ExecuteCapture(out savePath);
                //_notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Capture] " + Path.GetFileName(savePath), ToolTipIcon.Info);
                //_notifyIcon.Icon = Properties.Resources.MainIcon;
                CaptureImage();
            }
        }

        protected void ShowConfirmDialog(string savePath)
        {
            string fileName = Path.GetFileNameWithoutExtension(savePath);
            ConfirmForm saveForm = new ConfirmForm();
            Image sampleImage = new Bitmap(saveForm.ImageSampleSize.Width, saveForm.ImageSampleSize.Height, PixelFormat.Format24bppRgb);

            using (Image image = Image.FromFile(savePath))
            {
                using (Graphics g2 = Graphics.FromImage(sampleImage))
                {
                    g2.DrawImage(image, new Rectangle(Point.Empty, saveForm.ImageSampleSize), new Rectangle(Point.Empty, image.Size), GraphicsUnit.Pixel);
                }
            }

            saveForm.OldPath = savePath;
//            saveForm.FileName = fileName;
            if (Properties.Settings.Default.MemoryBeforeName && Properties.Settings.Default.BeforePath.Length > 0)
            {
//                saveForm.FileName = Path.GetFileNameWithoutExtension(Properties.Settings.Default.BeforePath);
                string nameTemp = Path.GetFileNameWithoutExtension(Properties.Settings.Default.BeforePath);
                long currentNum = 0;
                int paddingSize = 0;
                if (Regex.IsMatch(nameTemp, "[0-9]+$"))
                {
                    string numText = Regex.Match(nameTemp, "[0-9]+$").Value;
                    long.TryParse(numText, out currentNum);
                    nameTemp = nameTemp.Substring(0, nameTemp.Length - numText.Length);
                    paddingSize = numText.Length;
                }
                string nextNum = (currentNum + 1).ToString();
                paddingSize -= nextNum.Length;
                while (paddingSize-- > 0)
                {
                    nameTemp += "0";
                }
                nameTemp += nextNum;
                saveForm.FileName = nameTemp;
            }
            else
            {
                saveForm.FileName = fileName;
            }
            saveForm.ImageSample = sampleImage;
            if (saveForm.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            if (saveForm.FileName == fileName)
            {
                return;
            }
//            string fileName = saveForm.FileName;
//            string movePath = Path.Combine(Path.GetDirectoryName(savePath), fileName) + Path.GetExtension(savePath);
            string movePath = saveForm.NewPath;
            try
            {
                if (saveForm.Overwrite)
                {
                    File.Delete(movePath);
                }
                File.Move(savePath, movePath);
            }
            catch (IOException ioe)
            {
                MessageBox.Show(ioe.Message, Application.ProductName);
                return;
            }
            _notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Rename] " + Path.GetFileName(movePath), ToolTipIcon.Info);
            Properties.Settings.Default.BeforePath = movePath;
            Properties.Settings.Default.Save();
        }

        protected void CaptureImage()
        {
            SystemSounds.Asterisk.Play();
            _notifyIcon.Icon = Properties.Resources.MainIconCapture;
            string savePath = _makePath.GetNextFilePath();

            _makePath.CreateFolder();
            _screenCapture.ExecuteCapture(savePath);
            _notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Capture] " + Path.GetFileName(savePath), ToolTipIcon.Info);
            _notifyIcon.Icon = Properties.Resources.MainIcon;

            if (Properties.Settings.Default.ShowConfirm)
            {
                ShowConfirmDialog(savePath);
            }

        }

        /*
		public enum CaptureKeys
		{
            None,
            PrintScreen,
            ScrollLock,
            Pause,
            MiddleButton,
            IMENonconvert,
            CapsLock,
            Insert,
            End,
            F1,
            F12,
            CtrlShiftC,
            EnumCount,
		}         */
        protected void _keyboardHook_KeyboardEvent(object sender, KeyboardHook.KeyboardHookEventArgs e)
        {
            //System.Diagnostics.Debug.WriteLine("key:" + e.KeyValue);
            bool doCapt = false;
            if (e.KeyData == Keys.PrintScreen && _captuerKey == SettingForm.CaptureKeys.PrintScreen)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.Scroll && _captuerKey == SettingForm.CaptureKeys.ScrollLock)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.Pause && _captuerKey == SettingForm.CaptureKeys.Pause)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.IMENonconvert && _captuerKey == SettingForm.CaptureKeys.IMENonconvert)
            {
                doCapt = true;
            }
            else if (e.KeyValue == (int)240 && _captuerKey == SettingForm.CaptureKeys.CapsLock)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.Insert && _captuerKey == SettingForm.CaptureKeys.Insert)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.End && _captuerKey == SettingForm.CaptureKeys.End)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.F1 && _captuerKey == SettingForm.CaptureKeys.F1)
            {
                doCapt = true;
            }
            else if (e.KeyData == Keys.F12 && _captuerKey == SettingForm.CaptureKeys.F12)
            {
                doCapt = true;
            }
            //else if (e.KeyData == Keys.C && e.Control && e.Shift && _captuerKey == SettingForm.CaptureKeys.CtrlShiftC)
            //{
            //    doCapt = true;
            //}

            if (doCapt)
            {
                //System.Diagnostics.Debug.WriteLine("capt:" + SettingForm.CaptureKeys.PrintScreen);
                e.Cancel = true;
                CaptureImage();
            }
            //if (e.Button == MouseButtons.Middle)
            //{
            //    System.Diagnostics.Debug.WriteLine("middle");
            //    e.Cancel = true;

            //    //                SystemSounds.Exclamation.Play();
            //    //                _notifyIcon.BalloonTipText = "Capture...";
            //    SystemSounds.Asterisk.Play();
            //    _notifyIcon.Icon = Properties.Resources.MainIconCapture;
            //    string savePath;
            //    _capture.ExecuteCapture(out savePath);
            //    _notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Capture] " + Path.GetFileName(savePath), ToolTipIcon.Info);
            //    _notifyIcon.Icon = Properties.Resources.MainIcon;
            //}
        }

        public void UpdateSetting()
        {
            string saveFolder = Properties.Settings.Default.BaseFolderPath;
            if (saveFolder.Length == 0)
            {
                saveFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }
            string saveFolderName = Properties.Settings.Default.SaveFolderName;

            if (saveFolderName.Length > 0)
            {
                saveFolder = Path.Combine(saveFolder, saveFolderName);
            }
            _makePath.Folder = saveFolder;
            _makePath.BaseName = Properties.Settings.Default.BaseFileName;

            string targetRange = Properties.Settings.Default.TargetRange;
            for (int index = 0; index < (int)SettingForm.TargetRanges.EnumCount; index++)
            {
                if (((SettingForm.TargetRanges)index).ToString() == targetRange)
                {
                    switch ((SettingForm.TargetRanges)index)
                    {
                        case SettingForm.TargetRanges.Client:
                            _screenCapture.TargetRange = ScreenCapture.TargetRanges.Client;
                            break;
                        case SettingForm.TargetRanges.FullScreen:
                            _screenCapture.TargetRange = ScreenCapture.TargetRanges.FullScreen;
                            break;
                        case SettingForm.TargetRanges.Window:
                            _screenCapture.TargetRange = ScreenCapture.TargetRanges.Window;
                            break;
                        default:
                            System.Diagnostics.Debug.Assert(false);
                            break;
                    }
                    break;
                }
            }
            string captureKeyName = Properties.Settings.Default.CaptureKey;
            for (int captNum = 0; captNum < (int)SettingForm.CaptureKeys.EnumCount; captNum++)
            {
                if (((SettingForm.CaptureKeys)captNum).ToString() == captureKeyName)
                {
                    _captuerKey = (SettingForm.CaptureKeys)captNum;
                    break;
                }
            }

            string imageFormatName = Properties.Settings.Default.ImageFormat;
            for (int formatNum = 0; formatNum < (int)SettingForm.ImageFormats.EnumCount; formatNum++)
            {
                if (((SettingForm.ImageFormats)formatNum).ToString() == imageFormatName)
                {
                    switch((SettingForm.ImageFormats)formatNum)
                    {
                        case SettingForm.ImageFormats.Bmp:
                            _screenCapture.FileType = ScreenCapture.FileTypes.Bmp;
                            break;
                        case SettingForm.ImageFormats.Jpg:
                            _screenCapture.FileType = ScreenCapture.FileTypes.Jpg;
                            break;
                        case SettingForm.ImageFormats.Png:
                            _screenCapture.FileType = ScreenCapture.FileTypes.Png;
                            break;
                    }
                    break;
                }
            }
            _makePath.FileExt = _screenCapture.FileType.ToString().ToLower();
        }

        private void MainForm_Load(object sender, EventArgs e)
		{
            _settingForm.MainForm = this;

			UpdateSetting();

			_mouseHook.Event += _mouseHook_MouseEvent;
            _keyboardHook.Event += _keyboardHook_KeyboardEvent;
            _mouseHook.Hook();
            _keyboardHook.Hook();
			Visible = false;
		}

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			_notifyIcon.Visible = false;
            _mouseHook.Dispose();
            _keyboardHook.Dispose();
		}

		private void MainForm_Resize(object sender, EventArgs e)
		{
			if (WindowState == FormWindowState.Minimized && Visible)
			{
                Visible = false;
                ShowInTaskbar = false;
            }
		}

		private void _exitMenuItem_Click(object sender, EventArgs e)
		{
			Close();
        }

        private void _notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            _settingMenuItem_Click(sender, e);
        }

        private void _okButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void _settingMenuItem_Click(object sender, EventArgs e)
        {
            _settingForm.Show();
            _settingForm.WindowState = FormWindowState.Normal;
        }

        private void _browseFolderMenuItem_Click(object sender, EventArgs e)
        {
            if(Directory.Exists(_makePath.Folder))
            {
                using (Process.Start(_makePath.Folder))
                {
                }
            }
        }

        private void _saveClipboardMenuItem_Click(object sender, EventArgs e)
        {
            SystemSounds.Asterisk.Play();
            _notifyIcon.Icon = Properties.Resources.MainIconCapture;
 
            _makePath.CreateFolder();
            string savePath = _makePath.GetNextFilePath();
            Image image = Clipboard.GetImage();
            if (image == null)
            {
                _notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Warning] " + "Clipboard is empty.", ToolTipIcon.Warning);
                _notifyIcon.Icon = Properties.Resources.MainIcon;
                return;
            }
            image.Save(savePath);

            _notifyIcon.ShowBalloonTip(10, Application.ProductName, "[Save] " + Path.GetFileName(savePath), ToolTipIcon.Info);
            _notifyIcon.Icon = Properties.Resources.MainIcon;

            if (Properties.Settings.Default.ShowConfirm)
            {
                ShowConfirmDialog(savePath);
            }
        }

        private void _aboutMenuItem_Click(object sender, EventArgs e)
        {
            string messsage = "Poton Capture Ver " + Application.ProductVersion;
            messsage += "\n";
            messsage += "Copyright (C) Beta.Ito 2009";
            MessageBox.Show(this, messsage, Application.ProductName);
        }
	}
}